package com.cynteka.cyfoman.ui.collection;

import com.cynteka.cyfoman.core.ValueObject;
import com.cynteka.cyfoman.ui.bind.FormBinder;
import com.cynteka.cyfoman.ui.collection.factory.GridCollectionFactory;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;

import java.util.List;

/**
 * User: Sergey
 * Date: 10.08.11
 * Time: 20:07
 */
public class SelectionBindToFormAction implements Command {

    private String collectionId;
    private Object form;
    private FormBinder formBinder = new FormBinder();

    public String getCollectionId() {
        return collectionId;
    }

    public void setCollectionId(String collectionId) {
        this.collectionId = collectionId;
    }

    public Object getForm() {
        return form;
    }

    public void setForm(Object form) {
        this.form = form;
    }

    public FormBinder getFormBinder() {
        return formBinder;
    }

    public void setFormBinder(FormBinder formBinder) {
        this.formBinder = formBinder;
    }

    @Override
    public boolean execute(Context context) throws Exception {
        String selectedCollectionId = (String) context.get(GridCollectionFactory.COLLECTION_ID_PARAM);
        if(collectionId.equals(selectedCollectionId)) {
            Object oBeans = context.get(GridCollectionFactory.SELECTED_OBJECTS_PARAM);
            if(oBeans instanceof List) {
                List beans = (List) oBeans;
                if(!beans.isEmpty() && beans.get(0) instanceof ValueObject) {
                    ValueObject bean = (ValueObject)beans.get(0);
                    formBinder.bind(bean, form);
                } else {
                    // TODO add logging
                }
            }
        }
        return false;
    }
}
